import Vue,{PropOptions,VNode} from 'vue';
import {event} from 'quasar';
import {MySet} from '../../../util/polyfill';
const {stopAndPrevent}=event;
/**
 * 开关
 * @author 唐国雄
 * @date 2021/6/17
 * 属性----------------------
 * v-model			当前值, any
 * :open			开启时内容, string
 * :close			关闭时内容, string
 * :val				当v-model为MySet时, 当前代表的值, any
 * :true-value		当v-model不为MySet时, 勾选的值, any
 * :false-value		当v-model不为MySet时, 未勾选的值, any
 * :width			开关宽度, number
 * :color			颜色, string
 * :disable			禁用, boolean
 * 事件----------------------
 * @input
 * 插槽----------------------
 * #open		开启时内容(比:open优先)
 * #close		关闭时内容(比:close优先)
 */
export default Vue.extend({
	name:'Toggle',
	props:{
		//当前值
		value:{
			required:true,
		} as PropOptions<unknown|MySet<unknown>>,
		//开启时内容
		open:String,
		//关闭时内容
		close:String,
		//当v-model为MySet时, 当前代表的值
		val:{},
		//当v-model不为MySet时, 勾选的值
		trueValue:{
			default:true
		},
		//当v-model不为MySet时, 未勾选的值
		falseValue:{
			default:false
		},
		//开关宽度
		width:{
			type:Number,
			default:38,
		},
		//颜色
		color:String,
		//禁用
		disable:Boolean,
	},
	computed:{
		classes():string{
			return 'lexmis-Toggle'+
				(this.checkStatus?' lexmis--true':' lexmis--false')+
				(this.disable?' lexmis--disable':' lexmis--hoverable');
		},
		//MySet模式
		modelIsArray():boolean{
			return this.val!==undefined&&this.value instanceof MySet;
		},
		//勾选状态
		checkStatus():boolean{
			const {value}=this;
			if(this.modelIsArray){
				return (value as MySet<unknown>).has(this.val);
			}
			return this.trueValue===value;
		},
	},
	methods:{
		$_lexmis_onClick(e:Event,blur:boolean=true){
			stopAndPrevent(e);
			if(this.disable) return;
			this.$emit('input',this.$_lexmis_nextValue());
			if(blur){
				(this.$el as HTMLElement).blur();
			}
		},
		$_lexmis_nextValue(){
			const {
				checkStatus,
				value,
				trueValue,
				falseValue,
			}=this;
			if(this.modelIsArray){
				if(checkStatus){
					(value as MySet<unknown>).delete(this.val);
				}else{
					(value as MySet<unknown>).add(this.val);
				}
				return value;
			}else{
				return checkStatus?falseValue:trueValue;
			}
		},
	},
	render(h):VNode{
		const {open,close}=this.$scopedSlots;
		const openContent=open?open(undefined):this.open;
		const closeContent=close?close(undefined):this.close;
		return h('div',{
			staticClass:this.classes,
			staticStyle:{
				width:this.width+'px',
				color:this.color,
			},
			attrs:{
				tabindex:this.disable?-1:0,
			},
			on:{
				click:this.$_lexmis_onClick,
				keydown:(e:KeyboardEvent) => {
					if(e.key===' '||e.key==='Enter'){
						this.$_lexmis_onClick(e,false);
					}
				}
			}
		},[
			h('div',{
				staticClass:'lexmis_but',
				staticStyle:{
					left:this.checkStatus?(this.width-14-2+'px'):null
				}
			}),
			this.checkStatus&&openContent
				?h('div',{
					staticClass:'lexmis_open'
				},openContent)
				:null,
			!this.checkStatus&&closeContent
				?h('div',{
					staticClass:'lexmis_close'
				},closeContent)
				:null,
		]);
	}
});
